﻿#include <iostream>
#include <string>
#include <WS2tcpip.h>
using namespace std;
#pragma comment(lib, "ws2_32.lib")
#pragma warning(disable:4996)

int main()
{
	// 1.初始化Winsock
	WSADATA ws;
	WSAStartup(MAKEWORD(2, 2), &ws);

	// 2.创建套接字
	int client = socket(AF_INET, SOCK_DGRAM, 0);
	if (client == -1) {
		cout << "创建套接字失败:" << errno << endl;
		return -1;
	}

	// 3.设置地址和端口
	sockaddr_in addr;
	addr.sin_family = AF_INET;
	inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr.S_un.S_addr);
	addr.sin_port = htons(8000);

	// 4.设置套接字属性为广播类型
	bool optval = true;
	setsockopt(client, SOL_SOCKET, SO_BROADCAST, (const char*)&optval, sizeof(optval));
	
	// 5.连接
	char buf[100] = { 0 };
	int seRet = sendto(client, buf, sizeof(buf), 0, (sockaddr*)&addr, sizeof(addr));
	if (seRet == -1) {
		cout << "连接失败:" << errno << endl;
		closesocket(client);
		return -1;
	}

	int addrSize = sizeof(addr);
	while (true)
	{
		memset(buf, 0, sizeof(buf));
		// 6.接收UDP数据
		int reRet = recvfrom(client, buf, sizeof(buf), 0, (sockaddr*)&addr, &addrSize);
		if (reRet == -1) {
			cout << "接收数据失败" << errno << endl;
			break;
		}
		cout << "接收到数据:" << buf << endl;

		// 7.发送UDP数据
		strcpy(buf, "我是客户端");
		int seRet = sendto(client, buf, sizeof(buf), 0, (sockaddr*)&addr, sizeof(addr));
		if (seRet == -1) {
			cout << "发送数据失败:" << errno << endl;
			break;
		}
		cout << "发送数据成功" << endl;

		Sleep(1);
	}

	closesocket(client);
	return 0;
}
